package top.chengdongqing.mishop.user.favorite

import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.Cacheable
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import top.chengdongqing.mishop.common.exception.DeletionFailedException
import top.chengdongqing.mishop.common.exception.NotAcceptableException
import top.chengdongqing.mishop.entities.UserFavorite
import top.chengdongqing.mishop.repositories.ProductRepository
import top.chengdongqing.mishop.repositories.ProductSKURepository
import top.chengdongqing.mishop.repositories.UserFavoriteRepository

@Service
class FavoriteService(
    private val favoriteRepository: UserFavoriteRepository,
    private val productRepository: ProductRepository,
    private val skuRepository: ProductSKURepository
) {

    @Cacheable(value = ["user:favorites"], key = "#userId")
    fun findFavorites(userId: Int): List<FavoriteProductDTO> {
        val favorites = favoriteRepository.findAllByUserId(userId)
        return favorites.map { FavoriteProductDTO.of(it) }
    }

    fun existsFavorite(userId: Int, productId: Int): Boolean {
        return favoriteRepository.existsByProductIdAndUserId(productId, userId)
    }

    @CacheEvict(value = ["user:favorites"], key = "#userId")
    fun addFavorite(userId: Int, favoriteDTO: FavoriteProductDTO) {
        val product = productRepository.findByIdOrNull(favoriteDTO.productId)
        val sku = skuRepository.findByIdOrNull(favoriteDTO.skuId)

        if (product == null || sku == null) {
            throw NotAcceptableException("添加收藏失败：该商品不存在")
        }
        if (existsFavorite(favoriteDTO.productId, userId)) {
            throw NotAcceptableException("添加收藏失败：该商品已收藏")
        }

        val favorite = UserFavorite(
            userId = userId,
            product = product,
            sku = sku
        )
        favoriteRepository.save(favorite)
    }

    @Transactional
    @CacheEvict(value = ["user:favorites"], key = "#userId")
    fun removeFavorite(userId: Int, productId: Int) {
        if (favoriteRepository.deleteByProductIdAndUserId(productId, userId) == 0) {
            throw DeletionFailedException("删除商品收藏失败")
        }
    }
}